package com.example.flowermall.controller;

import com.example.flowermall.entity.Members;
import com.example.flowermall.entity.Orders;
import com.example.flowermall.entity.Result;
import com.example.flowermall.service.IOrderService;
import com.example.flowermall.service.MembersService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Members)表控制层
 *
 * @author mq
 * @since 2025-02-11 09:50:48
 */
@RestController
@RequestMapping("members")
public class MembersController {
    /**
     * 服务对象
     */
    @Resource
    private MembersService membersService;

    private final IOrderService orderService;

    public MembersController(IOrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Members> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.membersService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param members 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<Members> add(Members members) {
        return ResponseEntity.ok(this.membersService.insert(members));
    }

    /**
     * 编辑数据
     *
     * @param members 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<Members> edit(Members members) {
        return ResponseEntity.ok(this.membersService.update(members));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.membersService.deleteById(id));
    }

    /**
     * 查询单个用户的积分记录
     * */
    @GetMapping("/integral")
    public Result getIntegralList(@RequestParam Integer id){
        List<Members> integralList = membersService.getIntegralList(id);
        Double sum = 0D;
        for(Members members : integralList){
            Orders orders = orderService.getByOrderId(members.getOrderId());
            members.setOrders(orders);
            sum+=members.getAmount();
        }
        Result success = Result.success();
        success.put("data",integralList);
        success.put("total",sum);
        return success;
    }

    /**
     * 查询当个用户的余额记录
     * */
    @GetMapping("/balance")
    public Result getBalanceList(@RequestParam Integer id){
        List<Members> balanceList = membersService.getBalanceList(id);
        Double sum = 0D;
        for(Members members : balanceList){
            Orders orders = orderService.getByOrderId(members.getOrderId());
            members.setOrders(orders);
            sum += members.getAmount();
        }
        Result success = Result.success();
        success.put("data",balanceList);
        success.put("total",sum);
        return success;
    }

}

